package com.study.my.controller;

import com.study.my.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/users")
public class UserController {
    //创建线程安全的map
    static Map<Long,User> map = Collections.synchronizedMap(new HashMap<Long,User>());

    @GetMapping("/")
    public List<User> findUserList(){
        List<User> list = new ArrayList<>(map.values());
        return list;
    }

    @PostMapping("/")
    public String addUser(@ModelAttribute User user){
        map.put(user.getId(),user);
        return "success";
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id){
        User user = map.get(id);
        return user;
    }

    @PutMapping("/{id}")
    public String updateUser(@PathVariable Long id,@ModelAttribute User user){
        User u = map.get(id);
        u.setAge(user.getAge());
        u.setName(user.getName());
        map.put(id,u);
        return "success";
    }

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id){
        map.remove(id);
        return "success";
    }
}
